import { KeyValue } from "@/models/@types";
import Dexie, { Table } from "dexie";

export class ChatDB extends Dexie {
  private static _detabase = "hope-zaiwen";
  private _version = 1;
  _data!: Table<KeyValue>;

  private static _ins: ChatDB = new ChatDB();
  public static get ins(): ChatDB {
    return this._ins ? this._ins : (this._ins = new ChatDB());
  }

  constructor() {
    super(ChatDB._detabase);
    this.version(this._version).stores({
      _data: "key, str",
    });
  }
  /**  */
  async set(key: string, value: any = "{}") {
    const info = await this.getStr(key);
    if (info) {
      return await this._data.update(key, { value })
    } else {
      return await this._data.add({ key, value });
    }
  }
  /** 获取 */
  async getStr(key: string) {
    return await this._data?.get(key);
  }

  async clear() {
    return await this._data.clear();
  }
}

export const chatDB = ChatDB.ins;
